package com.tarry.task;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@ComponentScan("com.tarry")
@EnableAsync//启用异步支持
public class TaskExecutorConfig implements AsyncConfigurer {
    /**
     * The {@link Executor} instance to be used when processing async
     * method invocations.
     */
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //设置线程池维护的最少数量 即使线程池中的线程都处于空闲状态，也要创建新的线程来处理被添加的任务。
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);//设置线程池中的最大数量
        taskExecutor.setQueueCapacity(25);//缓存队列
        taskExecutor.setKeepAliveSeconds(200);//设置线程最大空闲时间
        taskExecutor.initialize();
        return taskExecutor;
    }

    /**
     * The {@link AsyncUncaughtExceptionHandler} instance to be used
     * when an exception is thrown during an asynchronous method execution
     * with {@code void} return type.
     */
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}
